<template>
  <div class="bed-dashboard" v-loading="loading">

    <header class="dashboard-header">
      <dv-decoration-8 style="width:300px;height:50px;" />
      <div class="title-container">
        <dv-decoration-7 style="width:400px;height:30px;">
          <span class="title-text">病床床位实时概览</span>
        </dv-decoration-7>
      </div>
      <dv-decoration-8 :reverse="true" style="width:300px;height:50px;" />
    </header>

    <div class="controls-container">
      <el-select
          v-model="selectedDepartment"
          placeholder="请选择科室"
          @change="fetchBedData"
          size="large"
          clearable
      >
        <el-option
            v-for="item in departmentOptions"
            :key="item.id"
            :label="item.roomName"
            :value="item.id"
        />
      </el-select>
    </div>

    <el-scrollbar class="main-content-scroll">
      <div class="main-content-wrapper">
        <dv-border-box-13
            v-for="ward in wardsData"
            :key="ward.wardId"
            class="ward-outer-box"
        >
          <div class="ward-content-area">
            <div class="ward-header-wrapper">
              <dv-decoration-6 style="width:150px;height:20px;">
                <span class="ward-title-text">{{ ward.wardName }}</span>
              </dv-decoration-6>
            </div>
            <div class="bed-grid">
              <div
                  v-for="bed in ward.beds"
                  :key="bed.bedId"
                  class="bed-card"
                  :class="{ 'occupied': bed.status === 1, 'empty': bed.status === 0 }"
                  @click="onBedClick(bed, ward)"
              >
                <div class="bed-no">{{ bed.bedNo }}</div>
                <div class="bed-status">
                  <span v-if="bed.status === 1">{{ bed.patientName }}</span>
                  <span v-else>空 闲</span>
                </div>
              </div>
            </div>
          </div>
        </dv-border-box-13>
        <div v-if="!selectedDepartment && !loading" class="empty-text">
          请先在顶部选择一个科室
        </div>
      </div>
    </el-scrollbar>

    <el-dialog
        v-model="diagnoseDialogVisible"
        :title="'病人工作站 - ' + currentPatient.patientName + ' (' + currentPatient.bedNo + ')'"
        width="80%"
        custom-class="data-v-dialog"
        append-to-body
        @close="handleModalClose"
        @opened="handleModalOpened"
    >
      <el-tabs v-model="activeTab" type="border-card" @tab-click="handleTabClick">

        <el-tab-pane label="病人信息" name="patientInfo">
          <el-descriptions
              title="患者档案"
              :column="2"
              border
              class="patient-info-descriptions"
          >
            <el-descriptions-item label="姓名">{{ currentPatient.patientName }}</el-descriptions-item>
            <el-descriptions-item label="年龄">{{ currentPatient.age }} 岁</el-descriptions-item>
            <el-descriptions-item label="性别">
              <span v-if="currentPatient.gender === 1">男</span>
              <span v-else-if="currentPatient.gender === 2">女</span>
              <span v-else>未知</span>
            </el-descriptions-item>
            <el-descriptions-item label="联系电话">{{ currentPatient.phone }}</el-descriptions-item>
            <el-descriptions-item label="入院科室">{{ currentPatient.roomName }}</el-descriptions-item>
            <el-descriptions-item label="入院病房">{{ currentPatient.wardName }}</el-descriptions-item>
            <el-descriptions-item label="病床号">{{ currentPatient.bedNo }}</el-descriptions-item>
            <el-descriptions-item label="主治医生">{{ currentPatient.doctorName }}</el-descriptions-item>
            <el-descriptions-item label="入院时间" :span="2">{{ currentPatient.admissionDate }}</el-descriptions-item>
          </el-descriptions>
        </el-tab-pane>

        <el-tab-pane label="编写医嘱" name="writeOrder">
          <el-input
              v-model="newOrderContent"
              type="textarea"
              :rows="5"
              placeholder="请输入医嘱内容..."
          ></el-input>
          <el-button type="primary" @click="submitNewOrder" style="margin-top: 15px;">提交医嘱</el-button>
          <el-divider />
          <span style="font-weight: bold;">历史医嘱</span>
          <el-table :data="patientOrders" max-height="300" v-loading="orderLoading">
            <el-table-column prop="content" label="医嘱内容" />
            <el-table-column prop="doctorName" label="开立医生" width="120" />
            <el-table-column prop="status" label="状态" width="100">
              <template #default="scope">
                <el-tag :type="scope.row.status == 0 ? 'warning' : 'success'">
                  {{ scope.row.status == 0 ? '待执行' : '已执行' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="nurseName" label="执行护士" width="120" />
          </el-table>
        </el-tab-pane>

        <el-tab-pane label="病例编写" name="writeCase">
          <el-input
              v-model="caseFileContent"
              type="textarea"
              :rows="20"
              placeholder="请在此处编写病人病例..."
              style="margin-top: 15px;"
          ></el-input>
          <el-button type="primary" @click="submitCaseFile" style="margin-top: 15px;">保存病例</el-button>
        </el-tab-pane>

        <el-tab-pane label="出院申请" name="applyDischarge">
          <div style="padding: 20px;">
            <p>病人姓名: <strong>{{ currentPatient.patientName }}</strong></p>
            <p>病床号: <strong>{{ currentPatient.bedNo }}</strong></p>
            <el-alert title="点击确定按钮，数据库表生成出院申请单，状态为申请中 0 " type="info" show-icon :closable="false" style="margin-top: 20px;"/>
            <el-button type="danger" @click="submitDischargeApplication" style="margin-top: 20px;">
              确认提交出院申请
            </el-button>
          </div>
        </el-tab-pane>

        <el-tab-pane label="手术申请" name="applySurgery" v-loading="surgeryTabLoading">
          <el-form :model="surgeryForm" :rules="surgeryRules" ref="surgeryFormRef" label-width="100px" style="margin-top: 20px; width: 80%;">
            <el-form-item label="手术项目" prop="surgeryItemId">
              <el-select
                  v-model="surgeryForm.surgeryItemId"
                  placeholder="请选择手术项目"
                  filterable
                  style="width: 100%;"
              >
                <el-option
                    v-for="item in allSurgeryItems"
                    :key="item.id"
                    :label="`${item.item_name} (¥${item.price})`"
                    :value="item.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="手术时间" prop="surgeryTime">
              <el-date-picker
                  v-model="surgeryForm.surgeryTime"
                  type="datetime"
                  placeholder="选择手术日期和时间"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  style="width: 100%;"
                  :disabled-date="disablePastDates"
                  :disabled-time="disableTime"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="submitSurgeryApplication">提交申请</el-button>
            </el-form-item>
          </el-form>
          <el-divider />
          <span style="font-weight: bold;">该患者的手术申请记录</span>
          <el-table :data="patientSurgeries" max-height="250">
            <el-table-column prop="surgeryItemName" label="手术项目" />
            <el-table-column prop="surgeryTime" label="拟定手术时间" width="200" />
            <el-table-column prop="status" label="状态" width="120">
              <template #default="scope">
                <el-tag :type="scope.row.status === 0 ? 'warning' : 'success'">
                  {{ formatSurgeryStatus(scope.row.status) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column fixed="right" label="Operations" min-width="120">
              <template #default="scope">
                <el-button :v-if="scope.row.status === 0 ? true : false" link type="primary" size="small" @click="handleClick(scope.row)">
                  审核
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

        <el-tab-pane label="开检查" name="openExam" v-loading="examTabLoading">
          <el-row :gutter="20">
            <el-col :span="12">
              <span style="font-weight: bold; color: white">选择检查项目</span>
              <el-table
                  :data="allExamItems"
                  max-height="400"
                  @selection-change="handleExamSelectionChange"
                  ref="examItemTableRef"
                  class="data-v-table"
              >
                <el-table-column type="selection" width="55" />
                <el-table-column prop="itemName" label="项目名称" />
                <el-table-column prop="price" label="价格(¥)" width="100" />
                <el-table-column prop="medicalRoomName" label="执行科室" width="150" />
              </el-table>
              <el-button type="primary" @click="submitNewExams" style="margin-top: 15px;">
                提交选中项目
              </el-button>
            </el-col>

            <el-col :span="12">
              <span style="font-weight: bold; color: white;">患者的检查记录</span>
              <el-table :data="patientExams" max-height="400" class="data-v-table">
                <el-table-column prop="itemName" label="项目名称" />
                <el-table-column prop="status" label="状态" width="100">
                  <template #default="scope">
                    <el-tag :type="formatExamStatusType(scope.row.status)">
                      {{ scope.row.status }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column prop="result" label="结果" />
                <el-table-column prop="finishTime" label="完成时间" width="160" />
              </el-table>
            </el-col>
          </el-row>
        </el-tab-pane>

        <el-tab-pane label="开药" name="prescribe" v-loading="drugTabLoading">
          <el-row :gutter="20">
            <el-col :span="12">
              <span style="font-weight: bold; color: black;">选择药品 (库存 > 0)</span>
              <el-table
                  :data="allDrugItems"
                  max-height="400"
                  class="data-v-table"
                  @row-click="onDrugRowClick"
              >
                <el-table-column prop="dsName" label="药名" />
                <el-table-column prop="dsBrand" label="品牌" width="120" />
                <el-table-column prop="dsOutprice" label="售价(¥)" width="100" />
                <el-table-column prop="dsStock" label="库存" width="80" />

                <el-table-column label="开药数量" width="160">
                  <template #default="scope">
                    <el-input-number
                        v-model="scope.row.quantity"
                        :min="0"
                        :max="scope.row.dsStock"
                        size="small"
                        controls-position="right"
                        @change="onDrugQuantityChange(scope.row)"
                    />
                  </template>
                </el-table-column>
              </el-table>
              <el-button type="primary" @click="submitNewPrescription" style="margin-top: 15px;">
                提交开药
              </el-button>
            </el-col>

            <el-col :span="12">
              <span style="font-weight: bold; color: black;">患者的开药记录</span>
              <el-collapse v-model="activeCollapse" accordion style="max-height: 450px; overflow-y: auto;">
                <el-collapse-item
                    v-for="p in patientPrescriptions"
                    :key="p.id"
                    :title="`${p.ppDate} - ${p.doctorName} (编号: ${p.ppNo})`"
                    :name="p.id"
                    class="data-v-collapse"
                >
                  <el-table :data="p.details" size="small" class="data-v-table">
                    <el-table-column prop="mdName" label="药名" />
                    <el-table-column prop="mdNum" label="数量" width="80" />
                    <el-table-column prop="mdBuyprice" label="单价" width="80" />
                  </el-table>
                </el-collapse-item>
              </el-collapse>
            </el-col>
          </el-row>
        </el-tab-pane>

      </el-tabs>
    </el-dialog>

  </div>
</template>

<script>
// 1. 引入所有需要的组件和API
import { ElMessage, ElMessageBox, ElDialog, ElTag, ElButton, ElSelect, ElOption, ElScrollbar, ElDatePicker, ElForm, ElFormItem, ElInput, ElTable, ElTableColumn, ElDivider, ElTabs, ElTabPane, ElAlert, ElDescriptions, ElDescriptionsItem, ElRow, ElCol } from 'element-plus';
import { loadBed, loadDepartment, loadPatientBed } from "../api/dashboard.js";
import {addRecord, queryByPatientId} from "../api/doctorOrder.js";
import { loadAllExamItems, loadPatientExams, submitPatientExams } from "../api/exam.js";
import {addCase} from "../api/case.js";
import {loadPatientSurgeries, submitSurgery, updateStatus} from "../api/surgery.js";
import { queryAllItem } from "../api/surgeryItem.js";
import { submitDischarge } from "../api/discharge.js";
import {loadAllDrugs, loadPatientPrescriptions, submitPrescription} from "../api/pharmacy.js";

export default {
  name: "BedDashboard",
  components: { ElDialog, ElTag, ElButton, ElSelect, ElOption, ElScrollbar, ElDatePicker, ElForm, ElFormItem, ElInput, ElTable, ElTableColumn, ElDivider, ElTabs, ElTabPane, ElAlert, ElDescriptions, ElDescriptionsItem, ElRow, ElCol },

  data() {
    return {
      // --- BedDashboard.vue ---
      departmentOptions: [],
      selectedDepartment: null,
      wardsData: [],
      loading: false,

      // --- InpatientDoctorStation.vue (弹窗相关) ---
      diagnoseDialogVisible: false,
      currentPatient: {},
      activeTab: 'patientInfo', // 默认显示病人信息

      // Tab: 医嘱
      patientOrders: [],
      newOrderContent: '',
      orderLoading: false,

      // Tab: 病例
      caseFileContent: '',

      // Tab: 手术
      surgeryTabLoading: false,
      surgeryForm: {
        surgeryItemId: null,
        surgeryTime: null
      },
      allSurgeryItems: [],
      patientSurgeries: [],
      surgeryRules: {
        surgeryItemId: [
          { required: true, message: '请选择一个手术项目', trigger: 'change' }
        ],
        surgeryTime: [
          { required: true, message: '请选择手术时间', trigger: 'change' }
        ]
      },

      // Tab: 检查
      examTabLoading: false,
      allExamItems: [],
      patientExams: [],
      selectedExamIds: [],

      // (为 "开药" Tab 更新 data)
      drugTabLoading: false,
      allDrugItems: [], // (药品列表, 会被添加 'quantity' 属性)
      patientPrescriptions: [], // (历史药方)
      activeCollapse: '', // (手风琴效果)
    };
  },

  methods: {
    async handleClick(row){
      let sid = row.id
      let {data:data} = await updateStatus({
        id:sid,
        sdStatus: 1
      })
      console.log(data)
    },
    // --- BedDashboard.vue 的方法 ---
    async loadDepartments() {
      try {
        let {data:response} = await loadDepartment()
        if (response && response.code === 200) {
          // 适配 el-select
          this.departmentOptions = response.obj.map(item => ({
            id: item.id,
            roomName: item.roomName
          }));
        } else {
          ElMessage.error(response.message || '获取科室列表失败');
        }
      } catch (error) {
        ElMessage.error('获取科室列表失败，请检查网络。');
      }
    },

    async fetchBedData() {
      let departmentId = this.selectedDepartment;
      if (!departmentId) {
        this.wardsData = [];
        return;
      }
      this.loading = true;
      this.wardsData = [];
      try {
        let {data:response} = await loadPatientBed(departmentId);
        if (response && response.code === 200) {
          this.wardsData = response.obj;
        } else {
          ElMessage.error(response.message || '获取病床数据失败');
        }
      } catch (error) {
        ElMessage.error("获取病床数据失败，请检查网络。");
      } finally {
        this.loading = false;
      }
    },

    // --- 核心改动：合并 handleBedClick 和 handleDiagnose ---
    onBedClick(bed, ward) {
      if (bed.status === 0) {
        ElMessage.info(`病床 [${bed.bedNo}] 为空闲`);
        return;
      }
      // 假设后端API (loadPatientBed) 已按要求返回所有字段
      if (!bed.patientId) {
        ElMessage.error("错误：该床位病人信息不全 (缺少 PatientId)，无法打开工作站。");
        console.error("点击的床位对象 'bed' 缺少 'patientId':", bed);
        return;
      }

      const currentDept = this.departmentOptions.find(
          dept => dept.id === this.selectedDepartment
      );
      const roomName = currentDept ? currentDept.roomName : '未知科室';

      // 组装 currentPatient 对象
      this.currentPatient = {
        // (来自 bed 对象)
        patientId: bed.patientId,
        patientName: bed.patientName,
        bedNo: bed.bedNo,
        age: bed.age,
        gender: bed.gender,
        phone: bed.phone,
        doctorName: bed.doctorName,
        admissionDate: bed.admissionDate,

        // (来自 ward 对象)
        roomName: roomName,
        wardName: ward.wardName,

        departmentId: this.selectedDepartment,

        diagnosis: bed.diagnosis || 'N/A' // (假设 bed 上有)
      };

      this.diagnoseDialogVisible = true;
    },


    // (弹窗打开后，不自动加载)
    async handleModalOpened() {
      // 默认显示 "病人信息" Tab，无需额外加载
    },

    // (弹窗关闭)
    handleModalClose() {
      this.currentPatient = {};
      this.activeTab = 'patientInfo'; // 重置回病人信息Tab
      this.newOrderContent = '';
      this.patientOrders = [];
      this.caseFileContent = '';
      this.examTabLoading = false;
      this.allExamItems = [];
      this.patientExams = [];
      this.selectedExamIds = [];
      this.surgeryTabLoading = false;
      this.allSurgeryItems = [];
      this.patientSurgeries = [];
      if (this.$refs.surgeryFormRef) {
        this.$refs.surgeryFormRef.clearValidate();
      }
      // (新增：重置开药Tab)
      this.drugTabLoading = false;
      this.allDrugItems = [];
      this.patientPrescriptions = [];
    },

    // (封装医嘱加载)
    async loadPatientOrders() {
      this.orderLoading = true;
      try {
        let {data:data} = await queryByPatientId(this.currentPatient.patientId);
        this.patientOrders = data.obj;
      } catch (error) {
        ElMessage.error("加载医嘱失败");
      } finally {
        this.orderLoading = false;
      }
    },

    // (封装检查Tab加载)
    async loadExamData() {
      if (!this.currentPatient.patientId) return;
      this.examTabLoading = true;
      try {
        const [itemsRes, historyRes] = await Promise.all([
          loadAllExamItems(),
          loadPatientExams(this.currentPatient.patientId)
        ]);

        if (itemsRes.data.code === 200) {
          this.allExamItems = itemsRes.data.obj;
        } else {
          ElMessage.error('加载可选检查失败: ' + itemsRes.data.message);
        }

        if (historyRes.data.code === 200) {
          this.patientExams = historyRes.data.obj;
        } else {
          ElMessage.error('加载病人检查历史失败: ' + historyRes.data.message);
        }

      } catch (error) {
        ElMessage.error("加载检查数据失败，请检查网络。");
      } finally {
        this.examTabLoading = false;
      }
    },

    // (封装手术Tab加载)
    async loadSurgeryData() {
      this.surgeryTabLoading = true;
      try {
        const [itemsRes, historyRes] = await Promise.all([
          queryAllItem(),
          loadPatientSurgeries(this.currentPatient.patientId)
        ]);

        if (itemsRes.data.code === 200) {
          this.allSurgeryItems = itemsRes.data.obj.map(item => ({
            id: item.id,
            item_name: item.itemName,
            price: item.price
          }));
        } else {
          ElMessage.error('加载手术项目失败: ' + itemsRes.data.message);
        }

        if (historyRes.data.code === 200) {
          this.patientSurgeries = historyRes.data.obj;
          console.log(historyRes)
        } else {
          ElMessage.error('加载手术历史失败: ' + historyRes.data.message);
        }

      } catch (error) {
        ElMessage.error('加载手术数据失败');
      } finally {
        this.surgeryTabLoading = false;
      }
    },

    // (封装开药Tab加载)
    async loadDrugData() {
      if (!this.currentPatient.patientId) return;
      this.drugTabLoading = true;
      try {
        const [itemsRes, historyRes] = await Promise.all([
          loadAllDrugs(),
          loadPatientPrescriptions(this.currentPatient.patientId)
        ]);
        if (itemsRes.data.code === 200) {
          // (重要：给每个药品对象添加 quantity 属性，用于 v-model)
          // (同时过滤掉无库存或下架的)
          this.allDrugItems = itemsRes.data.obj
              .filter(item => item.dsStatus === '1' && item.dsStock > 0)
              .map(item => ({
                ...item,
                quantity: 0
              }));
        } else {
          ElMessage.error('加载药品列表失败: ' + itemsRes.data.message);
        }

        if (historyRes.data.code === 200) {
          console.log(historyRes.data)
          this.patientPrescriptions = historyRes.data.obj;
        } else {
          ElMessage.error('加载病人开药历史失败: ' + historyRes.data.message);
        }

      } finally {
        this.drugTabLoading = false;
      }
    },

    // (Tab点击)
    async handleTabClick(tab) {
      const tabName = tab.paneName;

      if (tabName === 'writeOrder' && this.patientOrders.length === 0) {
        await this.loadPatientOrders();
      }
      else if (tabName === 'applySurgery' && this.allSurgeryItems.length === 0) {
        await this.loadSurgeryData();
      }
      else if (tabName === 'openExam' && this.allExamItems.length === 0) {
        await this.loadExamData();
      }
      // (新增：按需加载 "开药")
      else if (tabName === 'prescribe' && this.allDrugItems.length === 0) {
        await this.loadDrugData();
      }
    },

    // 提交新医嘱
    async submitNewOrder() {
      if (!this.newOrderContent) {
        ElMessage.warning('医嘱内容不能为空');
        return;
      }
      this.orderLoading = true;
      try {
        const order = {
          doCaseId: this.currentPatient.patientId,
          doContent: this.newOrderContent
        }
        await addRecord(order);
        ElMessage.success('新医嘱已提交');
        this.newOrderContent = '';
        await this.loadPatientOrders(); // 刷新
      } catch (error) {
        ElMessage.error('提交失败');
      } finally {
        this.orderLoading = false;
      }
    },

    // 保存病例
    async submitCaseFile() {
      if (!this.caseFileContent) {
        ElMessage.warning('病例内容不能为空');
        return;
      }
      await addCase({
        sid:1, // (TODO: 应从后端获取登录医生ID)
        patientId: this.currentPatient.patientId,
        description: this.caseFileContent
      })
      ElMessage.success('病例保存成功');
    },

    // 提交出院申请
    submitDischargeApplication() {
      ElMessageBox.confirm(
          `确定要为病人 [${this.currentPatient.patientName}] 提交出院申请吗?`,
          '出院申请确认',
          { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }
      ).then(async () => {
        try {
          const requestData = {
            patientId: this.currentPatient.patientId
          };

          const { data: response } = await submitDischarge(requestData);

          if (response.code === 200) {
            ElMessage.success('出院申请已提交，状态为申请中');

            // 刷新床位图 (病人状态可能变为 "待出院")
            await this.fetchBedData();
            this.diagnoseDialogVisible = false;
          } else {
            ElMessage.error(response.message || '申请失败');
          }

        } catch (err) {
          ElMessage.error(err.response?.data?.message || err.message || '申请失败，请重试');
        }
      }).catch(() => {});
    },

    // 提交手术申请
    submitSurgeryApplication() {
      this.$refs.surgeryFormRef.validate(async (valid) => {
        if (valid) {
          ElMessageBox.confirm(
              `确定要为 [${this.currentPatient.patientName}] 申请手术吗?`,
              '手术申请确认',
              { confirmButtonText: '确定', cancelButtonText: '取消', type: 'primary' }
          ).then(async () => {
            try {
              const request = {
                sdCaseId: this.currentPatient.patientId,
                sdSiId: this.surgeryForm.surgeryItemId,
                sdDate: this.surgeryForm.surgeryTime,
                sdStatus: 0
              };

              const { data: response } = await submitSurgery(request);

              if (response.code === 200) {
                ElMessage.success('手术申请提交成功!');
                // 刷新历史
                const { data: historyRes } = await loadPatientSurgeries(this.currentPatient.patientId);
                if (historyRes.code === 200) {
                  this.patientSurgeries = historyRes.data.obj;
                }
                this.$refs.surgeryFormRef.resetFields();
              } else {
                ElMessage.error(response.message || '申请失败');
              }

            } catch (err) {
              // ElMessage.error('申请失败，请重试');
            }
          }).catch(() => {});
        } else {
          ElMessage.warning('请检查表单，填写所有必填项');
        }
      });
    },

    // 格式化手术状态
    formatSurgeryStatus(status) {
      if (status === 0) return '申请中';
      if (status === 1) return '申请成功';
      return '未知';
    },

    // 提交新检查
    handleExamSelectionChange(selection) {
      this.selectedExamIds = selection.map(item => item.id);
    },
    async submitNewExams() {
      if (this.selectedExamIds.length === 0) {
        ElMessage.warning('请至少选择一个检查项目');
        return;
      }
      this.examTabLoading = true;
      try {
        const request = {
          patientId: this.currentPatient.patientId,
          examItemIds: this.selectedExamIds,
          status: "1",
          type: "1"
        };

        const { data: response } = await submitPatientExams(request);
        if (response.code === 200) {
          ElMessage.success('检查申请已提交');
          this.selectedExamIds = [];
          if (this.$refs.examItemTableRef) {
            this.$refs.examItemTableRef.clearSelection();
          }
          // 刷新历史
          const { data: historyRes } = await loadPatientExams(this.currentPatient.patientId);
          if (historyRes.code === 200) {
            this.patientExams = historyRes.obj;
          }
        } else {
          ElMessage.error(response.message || '提交失败');
        }
      } catch (error) {
        ElMessage.error('提交失败，请检查网络。');
      } finally {
        this.examTabLoading = false;
      }
    },
    formatExamStatusType(statusText) {
      if (statusText === '已完成') return 'success';
      if (statusText === '已缴费') return 'warning';
      if (statusText === '未缴费') return 'danger';
      return 'info';
    },

    // (开药Tab的方法)
    onDrugRowClick(row) {
      if (row.quantity === 0 && row.dsStock > 0) {
        row.quantity = 1;
      }
    },
    onDrugQuantityChange(row) {
      if (!row.quantity) {
        row.quantity = 0;
      }
    },
    // (提交新处方 - 批量)
    async submitNewPrescription() {
      // 1. 过滤出数量 > 0 的药品
      const selectedItems = this.allDrugItems
          .filter(item => item.quantity > 0)
          .map(item => ({
            drugId: item.id, // (对应 PrescriptionItemDTO)
            quantity: item.quantity
          }));

      if (selectedItems.length === 0) {
        ElMessage.warning('请至少选择一种药品并输入数量');
        return;
      }

      this.drugTabLoading = true;

      try {
        // (构造 CreatePrescriptionRequestDTO)
        const request = {
          patientId: this.currentPatient.patientId,
          items: selectedItems,
          type: "1" // 代表住院
        };

        // 2. 调用真实API (批量提交)
        const { data: response } = await submitPrescription(request);

        if (response.code === 200) {
          ElMessage.success('开药成功');
          // 3. 重新加载所有数据 (库存已变更, 历史已更新)
          await this.loadDrugData();
        } else {
          ElMessage.error(response.message || '开药失败');
          await this.loadDrugData(); // (失败也要刷新)
        }
      } catch (error) {
        ElMessage.error(error.response?.data?.message || '开药失败，请检查网络');
        await this.loadDrugData(); // (失败也要刷新)
      } finally {
        this.drugTabLoading = false;
      }
    },

    // 1. (修复) 手术申请禁用日期
    disablePastDates(time){
      // 获取今天的 00:00:00
      const today = new Date();
      today.setHours(0, 0, 0, 0);
      // 禁用所有早于今天 00:00:00 的日期
      return time.getTime() < today.getTime();
    },

    // 2. (移除) 旧的、错误的方法
    // disablePastHours(){ ... } // <--- 确保这一整个方法被删除

    // 3. (添加) 新的、正确的方法
    /**
     * 动态禁用时间 (小时和分钟)
     * @param {Date} date - 用户在日历上当前选择的日期
     */
    disableTime(date) {
      if (!date) {
        // 如果没有日期（例如刚打开选择器），不禁用任何时间
        return {};
      }

      const now = new Date();
      const selectedDate = new Date(date);
      const currentHour = now.getHours();
      const currentMinute = now.getMinutes();

      // 1. 检查是否选择了“今天”
      if (selectedDate.toDateString() === now.toDateString()) {

        // 如果是今天，则禁用当前小时之前的所有小时
        const disabledHours = () => {
          const hours = [];
          for (let i = 0; i < 24; i++) {
            if (i < currentHour) {
              hours.push(i);
            }
          }
          return hours;
        };

        // 并且，禁用“当前小时”的过去分钟
        const disabledMinutes = (hour) => {
          // 如果选的小时不是当前小时 (例如选了未来小时)，则不禁用分钟
          if (hour !== currentHour) {
            return [];
          }
          // 如果选的就是当前小时, 禁用过去的分钟
          const minutes = [];
          for (let i = 0; i < 60; i++) {
            if (i < currentMinute) {
              minutes.push(i);
            }
          }
          return minutes;
        };

        return {
          disabledHours: disabledHours,
          disabledMinutes: disabledMinutes,
        };

      } else {
        // 2. 如果选的是明天或未来日期
        // 不禁用任何小时或分钟
        return {};
      }
    }
  },

  created() {
    this.loadDepartments();
  }
};
</script>

<style scoped>
/* (所有 BedDashboard.vue 的样式都保留) */
.bed-dashboard {
  width: 100%;
  height: 100%;
  position: relative;
  background: url('https://data-v.oss-cn-hangzhou.aliyuncs.com/uploads/images/3a6f722c1dd14f63b208b5afd6543d88.png') no-repeat center center;
  background-size: cover;
  color: #fff;
  display: flex;
  flex-direction: column;
}
.dashboard-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 20px;
  height: 80px;
  flex-shrink: 0;
}
.title-container {
  display: flex;
  justify-content: center;
  align-items: center;
}
.title-text {
  font-size: 24px;
  font-weight: bold;
  margin: 0 10px;
  color: black;
}
.controls-container {
  padding: 10px 30px;
  text-align: left;
  flex-shrink: 0;
}
.controls-container :deep(.el-select .el-input__wrapper) {
  background-color: rgba(0, 0, 0, 0.3);
  border: 1px solid #0a5a9c;
  box-shadow: none;
}
.controls-container :deep(.el-select .el-input__inner) {
  color: #fff;
}
:global(.el-select-dropdown) {
  z-index: 3000 !important;
}

/* 主内容滚动区域 */
.main-content-scroll {
  flex: 1;
  padding: 0 30px;
  overflow: auto;
  --el-scrollbar-track-background: rgba(0, 0, 0, 0.2);
  --el-scrollbar-thumb-background: rgba(0, 229, 255, 0.5);
  --el-scrollbar-hover-background: rgba(0, 229, 255, 0.7);
}
.main-content-wrapper {
  padding: 20px 0;
}
.ward-outer-box {
  margin-bottom: 25px;
  padding: 10px;
  background-color: rgba(1, 12, 68, 0.4);
  border-radius: 6px;
}
.ward-content-area {
  padding: 5px 15px 15px 15px;
}
.ward-header-wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 40px;
  margin-bottom: 20px;
}
.ward-title {
  font-size: 18px;
  font-weight: bold;
  color: #00e5ff;
  margin-bottom: 15px;
  border-bottom: 1px solid rgba(0, 229, 255, 0.3);
  padding-bottom: 10px;
  text-align: center; /* 居中标题 */
}
.ward-title-text {
  font-size: 16px;
  font-weight: bold;
  color: black;
}
.bed-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(130px, 1fr));
  gap: 15px;
  padding: 0 10px;
}
.bed-card {
  height: 90px;
  border: 1px solid;
  border-radius: 8px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 0 8px rgba(0, 0, 0, 0.3);
}
.bed-card.empty {
  background-color: rgba(22, 160, 133, 0.3);
  border-color: #16a085;
}
.bed-card.empty:hover {
  transform: translateY(-3px) scale(1.03);
  box-shadow: 0 0 18px #16a085;
  background-color: rgba(22, 160, 133, 0.5);
}
.bed-card.occupied {
  background-color: rgba(192, 57, 43, 0.3);
  border-color: #c0392b;
}
.bed-card.occupied:hover {
  transform: translateY(-3px) scale(1.03);
  box-shadow: 0 0 18px #c0392b;
  background-color: rgba(192, 57, 43, 0.5);
}
.bed-no {
  font-size: 20px;
  font-weight: bold;
  color: #fff;
  text-shadow: 0 0 5px rgba(255, 255, 255, 0.7);
}
.bed-status {
  font-size: 14px;
  margin-top: 5px;
  color: rgba(255, 255, 255, 0.8);
}
.empty-text {
  text-align: center;
  font-size: 20px;
  margin-top: 100px;
  color: rgba(255, 255, 255, 0.7);
}
.patient-info-descriptions {
  margin: 10px;
}

/* 确保弹窗内的表格也应用 DataV 风格 */
.data-v-table {
  background-color: transparent;
  color: black;
}
:global(.data-v-dialog .el-table) {
  background-color: transparent !important;
  color: #fff !important;
}
:global(.data-v-dialog .el-table tr, .data-v-dialog .el-table th) {
  background-color: transparent !important;
  color: #fff !important;
  border-bottom: 1px solid rgba(0, 229, 255, 0.3) !important;
}
:global(.data-v-dialog .el-table--border::after, .data-v-dialog .el-table--group::after, .data-v-dialog .el-table::before) {
  background-color: rgba(0, 229, 255, 0.3) !important;
}
:global(.data-v-dialog .el-table__body-wrapper tbody tr:hover > td) {
  background-color: rgba(0, 229, 255, 0.1) !important;
}
:global(.data-v-dialog .el-table .el-table__cell) {
  background-color: transparent !important;
}
/* 确保 el-table 的 selection-box 也是亮的 */
:global(.data-v-dialog .el-checkbox__inner) {
  background: rgba(255, 255, 255, 0.1);
  border-color: #00e5ff;
}
:global(.data-v-dialog .el-checkbox__input.is-checked .el-checkbox__inner) {
  background: #00e5ff;
  border-color: #00e5ff;
}

/* DataV 风格的弹窗样式 */
:global(.data-v-dialog) {
  background-color: rgba(1, 12, 68, 0.9) !important;
  border: 1px solid #00e5ff !important;
  box-shadow: 0 0 20px rgba(0, 229, 255, 0.6) !important;
  color: #fff !important;
  border-radius: 8px !important;
}
:global(.data-v-dialog .el-dialog__header) {
  background-color: rgba(0, 229, 255, 0.2) !important;
  border-bottom: 1px solid rgba(0, 229, 255, 0.5) !important;
  padding: 15px 20px !important;
}
:global(.data-v-dialog .el-dialog__title) {
  color: #00e5ff !important;
  font-weight: bold !important;
  font-size: 18px !important;
}
:global(.data-v-dialog .el-dialog__close) {
  color: #fff !important;
}
/* 弹窗内的Tabs样式 */
:global(.data-v-dialog .el-tabs__content) {
  max-height: 60vh;
  overflow-y: auto;
  color: #fff; /* 确保Tab内容是亮的 */
}
:global(.data-v-dialog .el-tabs--border-card) {
  background: rgba(0, 229, 255, 0.1);
  border: 1px solid rgba(0, 229, 255, 0.3);
}
:global(.data-v-dialog .el-tabs--border-card > .el-tabs__header) {
  background-color: rgba(0, 229, 255, 0.2);
  border-bottom: 1px solid rgba(0, 229, 255, 0.3);
}
:global(.data-v-dialog .el-tabs__item) {
  color: #eee;
}
:global(.data-v-dialog .el-tabs__item.is-active) {
  color: #00e5ff;
  background: rgba(0, 229, 255, 0.3);
}
:global(.data-v-dialog .el-table) {
  background-color: transparent;
  color: #fff;
}
:global(.data-v-dialog .el-table tr, .data-v-dialog .el-table th) {
  background-color: transparent;
  color: #fff;
  border-bottom: 1px solid rgba(0, 229, 255, 0.3);
}
:global(.data-v-dialog .el-table--border::after, .data-v-dialog .el-table--group::after, .data-v-dialog .el-table::before) {
  background-color: rgba(0, 229, 255, 0.3);
}
:global(.data-v-dialog .el-table__body-wrapper tbody tr:hover > td) {
  background-color: rgba(0, 229, 255, 0.1) !important;
}
:global(.data-v-dialog .el-descriptions__label) {
  color: #00e5ff !important; /* 标签亮蓝色 */
  background: rgba(0, 229, 255, 0.1) !important;
}
:global(.data-v-dialog .el-descriptions__content) {
  color: #ffffff !important; /* 内容白色 */
  background: rgba(0, 229, 255, 0.05) !important;
}
:global(.data-v-dialog .el-descriptions__border .el-descriptions__cell) {
  border: 1px solid rgba(0, 229, 255, 0.3) !important;
}
:global(.data-v-dialog .el-descriptions__title) {
  color: #fff;
  font-weight: bold;
}
.dialog-content-wrapper p {
  line-height: 1.8;
  font-size: 15px;
}
.dialog-footer {
  text-align: right;
  padding-top: 10px;
}
.el-timeline {
  padding-left: 10px;
}
</style>